<template>
  <div v-loading="loading" class="preview-popover" :style="comStyle">
    <video
      ref="videoRef"
      :src="demoUrl"
      autoplay
      loop
      muted
      crossorigin="anonymous"
      @canplay="handleVideoCanplay"
    ></video>
  </div>
</template>
<script>
const PREVIEW_FATHER_CLASS = 'time-line-com';
const POPOVER_SIZE = {
  width: 258,
  height: 300,
};
export default {
  name: 'PreviewPopover',
  data() {
    return {
      show: false,
      demoUrl: '',
      loading: false,
      pos: {
        top: 0,
        left: 0,
      },
    };
  },
  computed: {
    comStyle() {
      const { width, height } = POPOVER_SIZE;
      return {
        top: `${this.pos.top}px`,
        left: `${this.pos.left}px`,
        display: this.show ? 'block' : 'none',
        width: `${width}px`,
        height: `${height}px`,
      };
    },
  },
  mounted() {
    document.body.appendChild(this.$el);
  },
  methods: {
    openPopover(item, el, demoUrl) {
      if (item && el && demoUrl) {
        this.show = true;
        this.demoUrl = demoUrl;
        this.loading = true;
        const pos = this.calcPopoverPos(el);
        Object.assign(this.pos, pos);
      }
    },
    closePopover() {
      if (this.show) {
        this.show = false;
        this.demoUrl = '';
        this.$refs.videoRef.removeAttribute('src');
        this.$refs.videoRef.load();
        this.loading = false;
      }
    },
    handleVideoCanplay() {
      if (this.demoUrl) {
        this.loading = false;
      }
    },
    calcPopoverPos(sonEl) {
      const offset = 8;
      const { width, height } = POPOVER_SIZE;
      const fatherEl = document.querySelector(`.${PREVIEW_FATHER_CLASS}`);
      const { left: fl, top: ft, width: fw } = fatherEl.getBoundingClientRect();
      const { left: sl, top: st, width: sw } = sonEl.getBoundingClientRect();
      let left = sl - fl + (sw - width) / Number('2') + fl;
      if (left + width > fw + fl) {
        left = fw + fl - offset - width;
      }
      const top = st - ft - height - offset + ft;
      return { left, top };
    },
  },
  beforeDestroy() {
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  },
};
</script>
<style scoped lang="stylus">
.preview-popover
  position absolute
  z-index 11
  width 258px
  height 300px
  border-radius 8px
  overflow hidden
  background #f5f7fa
  video
    width 100%
    height 100%
    object-fit cover
</style>
